﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace WindowsFormsApplication1
{
    public partial class Cotizalon : UserControl
    {
        public Cotizalon()
        {
            InitializeComponent();

            chart3.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;

            
            chart1.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;

            chart1.Series[0].IsXValueIndexed = true;

            chart1.Series[0].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
            chart1.Series[0].YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            chart1.ChartAreas.First().AxisY.LabelStyle.Format = "{0:$#,0.00}";
            chart1.ChartAreas.First().AxisX.LabelStyle.Format = "{0:hh:mm.ss}";
            chart1.Series[0]["PriceUpColor"] = "Green";
            chart1.Series[0]["PriceDownColor"] = "Red";


            dateTimePicker1.Value = DateTime.Now;

        }



        private void MostrarHistorico()
        {
            var db = Bolseye.Support.GetDB();

            var tickersObj = from t in db.Tickers
                             where t.Simbolo == _m_simboloID
                             orderby t.ID descending
                             select t;



            double minValue = double.MaxValue;
            double maxValue = double.MinValue;

            DateTime lastDate = DateTime.MinValue;

            var l = new List<Bolseye.Ticker>();

            foreach (var ticker in tickersObj.ToList())
            {
                var thisDate = new DateTime(ticker.Hora.Year, ticker.Hora.Month, ticker.Hora.Day);
                if (thisDate == lastDate) continue;
                lastDate = thisDate;

                l.Add(ticker);
            }

            l.Reverse();

            l.ForEach(ticker =>
            {
                DataPoint p = new DataPoint();

                p.XValue = ticker.Hora.ToOADate();
                p.YValues = new double[] { 
                    ticker.Maximo, 
                    ticker.Minimo, 
                    ticker.Apertura, 
                    ticker.Cierre 
                };

                chart3.Series[0].Points.Add(p);

                if (ticker.Minimo < minValue) minValue = ticker.Minimo;
                if (ticker.Maximo > maxValue) maxValue = ticker.Maximo;

            });

            chart3.ChartAreas.First().AxisY.Minimum = minValue;// *1.1d;
            chart3.ChartAreas.First().AxisY.Maximum = maxValue;// *0.9d;

        }



        double minValue = double.MaxValue;
        double maxValue = double.MinValue;
        int _m_simboloID;
        int _m_lastTickerID = -1;
        private void Cotizalon_Load(object sender, EventArgs e)
        {
            _m_simboloID = Bolseye.Support.ObtenerIDdeSimbolo(Bolseye.Support.GetDB(), Simbolo);

            MostrarHistorico();

            Timer t = new Timer();
            t.Interval = 1000;
            t.Tick += new EventHandler(t_Tick);
            t.Start();
        }


        void t_Tick(object sender, EventArgs e)
        {
            lblLastTick.Text = "Ultima Iteracion: " + DateTime.Now.ToString("dddd MM/dd/yyyy hh:mm:ss");
            Tick();
        }


        private void Tick()
        {

            var db = Bolseye.Support.GetDB();

            var date = dateTimePicker1.Value;

            var tickersObj = from t in db.Tickers
                             where t.Simbolo == _m_simboloID
                                && t.Hora.Day == date.Day
                                && t.Hora.Month == date.Month
                                && t.Hora.Year == date.Year
                                && t.ID > _m_lastTickerID
                             select t;

            var date2 = date.AddDays(-1);

            var cierreAnterior = (
                                from t in db.Tickers
                                where t.Simbolo == _m_simboloID
                                       && t.Hora.Day == date2.Day
                                       && t.Hora.Month == date2.Month
                                       && t.Hora.Year == date2.Year
                                orderby t.Hora descending
                                select t.Cierre
                                    ).FirstOrDefault();


            var tickers = tickersObj.ToList();

            if (tickers.Count == 0) return;

            lblActualizacion.Text = "Ultimo Tick en "+DateTime.Now.ToString("dddd MM/dd/yyyy hh:mm:ss");

            chart1.Series.First().ToolTip = "Cierre #VALY4 • Apertura #VALY3";

            double cierreActual = 0;

            tickersObj.ToList().ForEach(t =>
            {
                DataPoint p = new DataPoint();

                p.XValue= t.Hora.ToOADate();
                p.YValues = new double[] { t.Maximo, t.Minimo, t.Apertura, t.Cierre };

                chart1.Series[0].Points.Add(p);

                _m_lastTickerID = t.ID;

                if (t.Minimo < minValue) minValue = t.Minimo;
                if (t.Maximo > maxValue) maxValue = t.Maximo;

                lblMin.Text = Bolseye.Support.ValueToString(t.Minimo);
                lblMax.Text = Bolseye.Support.ValueToString(t.Maximo);
                lblAper.Text = Bolseye.Support.ValueToString(t.Apertura);
                lblCierre.Text = Bolseye.Support.ValueToString(t.Cierre);

                cierreActual = t.Cierre;
            });


            double varDiaria = Bolseye.Support.CalcularVariacionDiaria(cierreAnterior, cierreActual);

            lblDiaria.Text = Bolseye.Support.ValueToPercent(varDiaria);
            lblDiaria2.Text = Bolseye.Support.ValueToString(cierreActual - cierreAnterior);

            chart1.ChartAreas.First().AxisY.Minimum = minValue;// *1.1d;
            chart1.ChartAreas.First().AxisY.Maximum = maxValue;// *0.9d;

        }

        public string Simbolo { get; set; }

        private void chart1_GetToolTipText(object sender, ToolTipEventArgs e)
        {
            if (e.HitTestResult.PointIndex == -1) return;
            if (e.HitTestResult.PointIndex >= chart1.Series[0].Points.Count) return;
            DataPoint dp = chart1.Series[0].Points[e.HitTestResult.PointIndex];

            double aper = dp.YValues[2];
            double cierre = dp.YValues[3];

            double detha = cierre - aper;

            double var = (detha * 100 / aper);

            e.Text = Bolseye.Support.ValueToString(cierre) + " " + Bolseye.Support.ValueToPercent(var);
        }


        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            _m_lastTickerID = -1;

            chart1.Series[0].Points.Clear();

            minValue = double.MaxValue;
            maxValue = double.MinValue;
        }


        private void chart3_GetToolTipText(object sender, ToolTipEventArgs e)
        {
            if (e.HitTestResult.PointIndex == -1) return;
            if (e.HitTestResult.PointIndex >= chart3.Series[0].Points.Count) return;
            DataPoint dp = chart3.Series[0].Points[e.HitTestResult.PointIndex];

            double aper = dp.YValues[2];
            double cierre = dp.YValues[3];

            double detha = cierre - aper;

            double var = (detha * 100 / aper);

            e.Text = string.Format("C: {1}{0}A: {2}{0}Mi: {3}{0}Ma: {4}{0}",
                        Environment.NewLine,
                        Bolseye.Support.ValueToString(cierre),
                        Bolseye.Support.ValueToString(aper),
                        Bolseye.Support.ValueToString(dp.YValues[1]),
                        Bolseye.Support.ValueToString(dp.YValues[0])
                        );
            //+" " + Bolseye.Support.ValueToPercent(var);

        }


    }
}
